package zhoufu.sz.sanxiao_check.inject.modules;

import android.app.Activity;
import android.databinding.ObservableField;
import android.support.annotation.NonNull;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.reflect.TypeToken;
import dagger.Module;
import dagger.Provides;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import zhoufu.sz.sanxiao_check.inject.PerActivity;
import zhoufu.sz.sanxiao_check.inject.RetrofitQualifier;
import zhoufu.sz.sanxiao_check.net.RequestHelper;
import zhoufu.sz.sanxiao_check.net.RequestRepository;
import zhoufu.sz.sanxiao_check.utils.NetWorkUtil;
import zhoufu.sz.sanxiao_check.utils.SharedPreferencesUtil;

/**
 * Created by hyc on 16/5/5.
 *
 */
@Module
public class ActivityModule
{

    private final Activity _activity;
    private Gson _gson;

    public ActivityModule(Activity activity)
    {
        this._activity=activity;
    }
    @PerActivity
    @Provides  Activity provideActivity(){
        return this._activity;
    }     
    @NonNull private OkHttpClient getWxOkHttpClient(){
        return  new OkHttpClient().newBuilder().addInterceptor(CacheInterceptor()).
                cache(CacheBuild("wxCache")).build();
    }
    @NonNull private OkHttpClient getGKOkHttpClient(){
        return  new OkHttpClient().newBuilder().addInterceptor(CacheInterceptor()).
                cache(CacheBuild("gkCache")).build();
    }
    @NonNull private OkHttpClient getZHOkHttpClient(){
        return  new OkHttpClient().newBuilder().addInterceptor(CacheInterceptor()).
                cache(CacheBuild("zhCache")).build();
    }

    private Cache CacheBuild(String fileName)
    {
        File targetStore = new File(_activity.getExternalCacheDir(), fileName);
        int  maxSize     = 1024 * 1024 * 10;// 10m
        return  new Cache(targetStore, maxSize);

    }

    public static final String WXBASEURL = "http://api.huceo.com/wxnew/";




    @Provides
    public SharedPreferencesUtil provideSharedPreferencesUtil(Activity app){
        return new SharedPreferencesUtil(app);
    }

    @Provides
    public RequestHelper provideRequestHelper(Activity context){
        return new RequestHelper(context);
    }

    @Provides
    public RequestRepository provideRequestRepository(Activity context,Gson gson){
        return new RequestRepository(context,gson);
    }

    @Provides
    public Gson provideGson(){
        return new Gson();
    }
    @Provides
    @RetrofitQualifier("Observable")
    public Gson provideObGson(){
        GsonBuilder gsonBuilder=new GsonBuilder();
        gsonBuilder.registerTypeAdapter(new TypeToken<ObservableField<String>>(){}.getType(),new ObservableFieldSerializerDeserializer());
        gsonBuilder.registerTypeAdapter(new TypeToken<ObservableField<Integer>>(){}.getType(),new ObservableFieldSerializerDeserializer());
        _gson = gsonBuilder.create();
        return _gson;
    }

    private  class ObservableFieldSerializerDeserializer implements JsonSerializer<ObservableField>,JsonDeserializer<ObservableField> {

        @Override
        public JsonElement serialize(ObservableField src, Type typeOfSrc, JsonSerializationContext context) {
            return context.serialize(src.get());
        }

        @Override
        public ObservableField deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            final Type type = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];
            return new ObservableField(_gson.fromJson(json, type));
        }
    }
    private Interceptor CacheInterceptor()
    {
        return new Interceptor()
        {
            @Override public Response intercept(Chain chain) throws IOException
            {
                // 拿到 数据
                Request request = chain.request();
                HttpUrl url     = request.url();
                if (!NetWorkUtil.isNetWorkAvailable(_activity)){
                    request= request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).url(url).build();
                }else {
                    request=request.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).url
                            (url).build();
                }
                Response response = chain.proceed(request);
                //根据当前的 网络状况来 决定数据来源
                if (NetWorkUtil.isNetWorkAvailable(_activity))
                {
                    int maxSeconds = 60;//1min
                    return response.newBuilder().removeHeader("Pragma")
                            .removeHeader("Cache-Control")
                            .addHeader("Cache-Control", "Public , max-age = " + maxSeconds)
                            .build();
                } else
                {
                    int maxTime = 3600 * 12;//12小时
                    return response.newBuilder().removeHeader("Pragma")
                            .removeHeader("Cache-Control")
                            .addHeader("Cache-Control",
                                    "Public , only-if-cached, max-age = " + maxTime)
                            .build();
                }
            }
        };
    }   
    
}
